package com.wangxiaonan.wxwork.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.domain.Appchat;
import com.wangxiaonan.wxwork.domain.AppchatCriteria;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.repository.AppchatDao;
import com.wangxiaonan.wxwork.service.AppChatService;
import com.wangxiaonan.wxwork.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class AppChatServiceImpl implements AppChatService {
    private static final Logger logger = LoggerFactory.getLogger(AppChatServiceImpl.class);

    @Resource
    private AppchatDao appChatDao;

    @Override
    public JSONObject createAppChat(String token, String jsonParam) {
        logger.info("[AppChatServiceImpl] createAppChat >> jsonParam: {}", jsonParam);
        if (StringUtils.isBlank(token)) {
            logger.error("[AppChatServiceImpl] createAppChat >> token: {}", token);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(AppChatService.POST_APP_CHAT_CREATE_URL, token);
            result = HttpUtil.post(url, jsonParam);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[AppChatServiceImpl] createAppChat >> result: {}", result);
            throw new ServiceException("object_format_error", "请求结果格式化错误");
        }

        return json;
    }

    @Override
    public JSONObject updateAppChat(String token, String jsonParam) {
        logger.info("[AppChatServiceImpl] updateAppChat >> jsonParam: {}", jsonParam);
        if (StringUtils.isBlank(token)) {
            logger.error("[AppChatServiceImpl] updateAppChat >> token: {}", token);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(AppChatService.POST_APP_CHAT_UPDATE_URL, token);
            result = HttpUtil.post(url, jsonParam);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[AppChatServiceImpl] updateAppChat >> result: {}", result);
            throw new ServiceException("object_format_error", "请求结果格式化错误");
        }

        return json;
    }

    @Override
    public JSONObject getAppChat(String token, String chatId) {
        logger.info("[AppChatServiceImpl] getAppChat >> chatId: {}", chatId);
        if (StringUtils.isBlank(token)) {
            logger.error("[AppChatServiceImpl] getAppChat >> token: {}", token);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(AppChatService.GET_APP_CHAT_GET_URL, token, chatId);
            result = HttpUtil.get(url);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[AppChatServiceImpl] getAppChat >> result: {}", result);
            throw new ServiceException("object_format_error", "请求结果格式化错误");
        }

        return json;
    }

    @Override
    public JSONObject sendMessage(String token, String jsonParam) {
        logger.info("[AppChatServiceImpl] sendMessage >> jsonParam: {}", jsonParam);
        if (StringUtils.isBlank(token)) {
            logger.error("[AppChatServiceImpl] sendMessage >> token: {}", token);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(AppChatService.POST_APP_CHAT_SEND_URL, token);
            result = HttpUtil.post(url, jsonParam);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[AppChatServiceImpl] sendMessage >> result: {}", result);
            throw new ServiceException("object_format_error", "请求结果格式化错误");
        }

        return json;
    }

    @Override
    public Appchat queryById(String chatId) {
        logger.info("[AppChatServiceImpl] sendMessage >> queryById: {}", chatId);
        if (StringUtils.isBlank(chatId)) {
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }

        return appChatDao.selectByPrimaryKey(chatId);
    }

    @Override
    public List<Appchat> queryByAgentId(String agentId) {
        logger.info("[AppChatServiceImpl] queryByAgentId >> agentId: {}", agentId);
        if (StringUtils.isBlank(agentId)) {
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        AppchatCriteria ac = new AppchatCriteria();
        AppchatCriteria.Criteria criteria = ac.createCriteria();
        criteria.andAgentIdEqualTo(agentId);
        return appChatDao.selectByCriteria(ac);
    }

    @Override
    public int saveAppChat(Appchat appChat) {
        if (appChat == null || StringUtils.isBlank(appChat.getAgentId())
                || StringUtils.isBlank(appChat.getChatId())
                || StringUtils.isBlank(appChat.getChatName())) {
            logger.error("[AppChatServiceImpl] saveAppChat >> appChat is invalid");
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        return appChatDao.insert(appChat);
    }

    @Override
    public JSONObject saveAndCreateAppChat(Appchat appChat, String token, String jsonParam) {
        if (appChat == null || StringUtils.isBlank(appChat.getAgentId())
                || StringUtils.isBlank(appChat.getChatId())
                || StringUtils.isBlank(appChat.getChatName())) {
            logger.error("[AppChatServiceImpl] saveAppChat >> appChat is invalid");
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        int result = appChatDao.insert(appChat);
        JSONObject jsonObject = new JSONObject();
        if (result > 0) {
            jsonObject = createAppChat(token, jsonParam);
            String errcode = jsonObject.getString("errcode");
            if (!"0".equals(errcode)) {
                logger.error(jsonObject.toJSONString());
                throw new ServiceException("create_chat_error", "创建群聊失败");
            }
        } else {
            throw new ServiceException("create_chat_error", "群聊信息保存数据库失败");
        }
        return jsonObject;
    }
}
